//
//  UIViewController+Store.m
//  GK
//
//  Created by Seven on 2019/5/6.
//  Copyright © 2019 Seven. All rights reserved.
//

#import "UIViewController+Store.h"

@implementation UIViewController(Store)


#pragma mark - presentProductVC

- (void)presentProductInfoWithUrl:(id)url{
    NSURL *pUrl = url;
    if ([url isKindOfClass:[NSString class]]) {
        pUrl = [NSURL URLWithString:url];
    }
    NSString *productid = pUrl.lastPathComponent;
    if ([productid hasPrefix:@"id"]) {
        productid = [productid substringFromIndex:2];
    }
    [self presentProductInfoWithId:productid];
}
//pId 是APP在AppleStore上的id
- (void)presentProductInfoWithId:(NSString *)pId
{
    SKStoreProductViewController *spCtrl = [[SKStoreProductViewController alloc] init];
    //有一个代理方法，在完成／取消购买操作的时候调用，可以用于返回之前的页面
    spCtrl.delegate = self;
    [spCtrl loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier:pId}
                      completionBlock:^(BOOL result, NSError *error) {
                          if (result)
                          {
                              
                          } else
                          {
                              NSLog(@"%@", error);
                          }
                      }];
    //In most cases, you should load the product information and then present the view controller. However, if you load new product information while the view controller is presented, the contents of the view controller are replaced after the new product data is loaded. -- 摘自官方文档
    //由于loadProductWithParameters是同步的，有时候需要等很久才会block回调，所以直接弹出控制器，等到信息获取到之后，会自动刷新弹出的控制器界面内容
    [self presentViewController:spCtrl
                       animated:YES
                     completion:nil];
}

#pragma mark - SKStoreProductViewControllerDelegate
//在代理方法中，将视图dismiss
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
